<?php
/**
 * Created by PhpStorm.
 * Script Name: Groupmember.php
 * Create: 2021/12/21 12:00
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\BotWhiteid as WhiteidM;
use plugin\wechat\app\model\BotMember as MemberM;
use plugin\wechat\app\model\BotGroupmember;
use plugin\wechat\app\TenantController;
use Support\Request;

class Botwhiteid extends TenantController
{
    /**
     * @var WhiteidM
     */
    protected $model;
    /**
     * @var BotGroupmember
     */
    private $groupMemberM;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new WhiteidM();
        $this->groupMemberM = new BotGroupmember();
    }

    public function index()
    {
        $bot = \request()->botInfo;
        $group = MemberM::where([$this->tenantWhere()])
            ->find(input('group_id', 0));
        if (!$group) {
            return $this->error('参数错误');
        }
        $data = $this->model->where([
                $this->tenantWhere(),
                ['bot_id' ,'=', $bot['id']],
                ['group_wxid','=', $group['wxid']]
            ])
            ->find();

        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $data['group_wxid'] = $group['wxid'];
        $data['bot_id'] = $bot['id'];

        $members = $this->groupMemberM->where([
            $this->tenantWhere(),
            ['group_id' ,'=', $group['id']]
        ])
            ->column('nickname', 'wxid');
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('设置白名单')
            ->setTip("白名单成员即使触发了踢除机制也不会被移除")
            ->setPostUrl(url('savePost'))
            ->addFormItem('bot_id', 'hidden', 'bot_id', 'bot_id')
            ->addFormItem('group_wxid', 'hidden', 'group_wxid', 'group_wxid')
            ->addFormItem('wxids', 'chosen_multi', '选择群友', '选择群友', $members, 'required')
            ->setFormData($data);
        !empty($data) && $builder->addFormItem('id', 'hidden', 'ID', 'ID');
        return $builder->show();
    }

    public function savePost(Request $request, $jump_to = '', $data = [])
    {
        $post_data = input('post.');
        $post_data['company_id'] = TenantService::getCompanyId();
        if(empty($post_data[$this->pk])){
            $res = $this->model->createOne($post_data);
        }else {
            $res = $this->model->update($post_data);
        }
        if($res){
            return $this->success('操作成功!', $jump_to);
        }else{
            return $this->error('操作失败!', '', ['token' => token()]);
        }
    }
}